<?php

/**
 * alltosun.com 购物车函数 cart_helper.php
 * ============================================================================
 * 版权所有 (C) 2009-2014 北京互动阳光科技有限公司，并保留所有权利。
 * 网站地址: http://www.alltosun.com
 * ----------------------------------------------------------------------------
 * 许可声明: 这是一个开源程序，未经许可不得将本软件的整体或任何部分用于商业用途及再发布。
 * ============================================================================
 * $Author: 吴松键 (wusj@alltosun.com) $
 * $Date: 2014-9-10 下午4:17:39 $
 * $Id$
 */
class cart_helper
{
    public static function get_list()
    {
        $cart_list = unserialize(Cookie::get('cart'));
        $user_id   = user_helper::get_user_id();

        if ($user_id > 0) {
            if (!empty($cart_list)) {
                $filter['user_id'] = $user_id;
                $cart_online_list = _model('cart')->getList($filter);

                // 获取数据库内的sku_ids
                foreach ($cart_online_list as $k => $v) {
                    $sku_ids[] = $v['sku_id'];
                }

                foreach ($cart_list as $k => $v) {
                    if ($v['is_promotion'] > 0) {
                        continue;
                    }

                    if (!empty($sku_ids) && in_array($v['sku_id'], $sku_ids)) {
                        $info = array(
                            'is_promotion' => $v['is_promotion'],
                            'is_gift'=>$v['is_gift'],
                            'goods_id' => $v['goods_id'],
                            'goods_num' => $v['goods_num']
                            );
                        _model('cart')->update(array('user_id' => $user_id, 'sku_id' => $v['sku_id']), $info);
                        continue;
                    }

                    $info = $v;
                    $info['user_id'] = $user_id;
                    _model('cart')->create($info);
                }

                Cookie::set_path(Config::get('cookie_path'));
                Cookie::set_domain(Config::get('cookie_domain'));
                Cookie::del('cart');
            }

            $cart_list = _model('cart')->getList(array('user_id' => $user_id));
        }

        if (empty($cart_list)) {
            return array();
        }

        return $cart_list;
    }

    /**
     * 合并购物车 并返回列表
     */
    public static function cart_merge()
    {
        $user_id   = user_helper::get_user_id();
        $cart_list = self::get_list();
        if (empty($cart_list)) {
            return array();
        }

        // 过滤失效商品
        foreach ($cart_list as $k => $v) {
            $goods_info = _uri('goods', $v['goods_id']);
            $sku_info = _uri('sku', $v['sku_id']);

            $promotion_add_fail = 0; // 加价购商品是否失效
            $promotion_add_info = _model('promotion_add')->read(array('goods_id'=>$v['goods_id']));
            if ($v['is_promotion'] && (!$promotion_add_info || empty($promotion_add_info))) {
                $promotion_add_fail = 1;
            }

            // liw add is_direct_buy =1 过滤
            if (!$v['sku_id'] || empty($sku_info)|| !$v['goods_id'] || !$v['goods_num'] || !$goods_info['status'] || !$goods_info['is_sale'] || $goods_info['is_direct_buy']==1 || $promotion_add_fail) {
                if ($user_id > 0) {
                    _model('cart')->delete($v['id']);
                }
                unset($cart_list[$k]);
            } else if ($v['is_gift'] == 1) { // 过滤失效的 赠品
                if ($gift_num = cart_helper::get_sku_num($v['parent_sku_id'])) {
                    $gift_nums = _uri('goods_gift_relation', array('goods_id'=>$v['parent_id'], 'gift_sku_id'=>$v['sku_id']), 'gift_num');
                    if ($cart_list[$k]['goods_num'] == $gift_num*$gift_nums) {
                        continue;
                    }
                    $cart_list[$k]['goods_num'] = $gift_num*$gift_nums;
                    if ($user_id > 0) {
                        _model('cart')->update(array('id'=>$v['id']), array('goods_num'=>$cart_list[$k]['goods_num']));
                    }
                } else {
                     if ($user_id > 0) {
                        _model('cart')->delete($v['id']);
                    }
                    unset($cart_list[$k]);
                }
            }
        }

        // 列表排序
        $new_list = array();
        foreach ($cart_list as $k=>$v) {
            if ($v['is_promotion'] == 0 && $v['is_gift'] == 0) {
                $new_list[] = $v;
            }
        }
        foreach ($cart_list as $k=>$v) {
            if ($v['is_promotion'] == 1) {
                $new_list[] = $v;
            }
        }
        foreach ($cart_list as $k=>$v) {
            if ($v['is_promotion'] == 0 && $v['is_gift'] == 1) {
                $new_list[] = $v;
            }
        }

        // 重新存入cookie
        if (!$user_id) {
            Cookie::set_path(Config::get('cookie_path'));
            Cookie::set_domain(Config::get('cookie_domain'));
            Cookie::set('cart', serialize($new_list), time() + 7*24*3600);
        }

        return $new_list;
    }

    /**
     * 返回商品总价
     */
    public static function get_cart_price_total($is_format = 1, $is_discount = 0, $is_promotion = 1, $cart_list = NULL, $pay_account_id = false)
    {
        if(NULL === $cart_list) {
            if($pay_account_id !== false) {
                $alipay_account_list = Config::get('alipay_account_list');
                $category_cart_list = cart_helper::category_cart_by_alipay_account();
                $cart_list = $category_cart_list[$pay_account_id];
            } else {
                $cart_list = cart_helper::cart_merge();
            }
        }
        
        $price_total = 0;
        foreach ($cart_list as $k => $v) {
            if ($v['is_gift'] == 1) {
                continue;
            }

            $price = _uri('sku', $v['sku_id'], 'price');
            if ($v['is_promotion'] > 0) {
                if ($is_promotion == 1) { // 是否获取加价购商品总价
                    $goods_id = _uri('sku', $v['sku_id'], 'goods_id');
                    $price = _uri('promotion_add', array('goods_id'=>$goods_id), 'sale_price');
                    $v['goods_num'] = 1;
                } else {
                    continue;
                }
            }

            $price_total += (int)$v['goods_num'] * $price;
        }

        if ($is_discount == 1) {
            $offer_price = promotion_helper::get_curr_promotion($price_total);
            $price_total -= $offer_price;
            if ($price_total < 0) {
                $price_total = 0;
            }
        }

        if ($is_format) {
            return number_format($price_total, 2);
        } else {
            return $price_total;
        }
    }

    /**
     * 商品能不能加入购物车
     * @return bool|string err_msg
     */
    public static function can_add_cart($goods_id)
    {
        $goods_id = (int)$goods_id;
        if(!$goods_id) {
            return '商品不存在';
        }
        $goods_info = _uri('goods', $goods_id);
        if (!$goods_info || !$goods_info['is_sale']) {
            return '当前商品以下架';
        }
        if($goods_info['is_direct_buy'] == 1) {
            return "此商品不能加入购物车，请直接下单购买";
        }

        return true;
    }

    /**
     * 获取商品订单总价
     */
    public static function get_order_total($express_price = 0, $coupon_code = '')
    {
        if(isset($_SESSION['order_pay_account'])) {
            $pay_account_id = (int)$_SESSION['order_pay_account'];
        } else {
            $pay_account_id = false;
        }
        $price = self::get_cart_price_total(0, 1, 1, NULL, $pay_account_id) + $express_price;

        if ($coupon_code) {
            $price -= coupon_helper::get_coupon_use_price($coupon_code);
        }
        if ($price < 0) {
            return 0;
        }

        return $price;
    }

    /**
     * 获取购物车商品总数量
     */
    public static function get_cart_num($is_all = 0)
    {
        $cart_list = self::cart_merge();

        if (empty($cart_list)) {
            return 0;
        }

        $count = 0;
        foreach ($cart_list as $k => $v) {
            if ($v['is_gift'] > 0) {
                continue;
            }
            if ($v['is_promotion'] > 0 && !$is_all) {
                continue;
            }
            if ($v['is_promotion'] > 0 && $is_all) {
                $v['goods_num'] = 1;
            }
            $count += $v['goods_num'];
        }

        return $count;
    }

    /**
     * 获取折扣
     * @param  int
     * @param  int
     * @return float
     */
    public static function get_discount($price, $discount)
    {
        if (!$discount || !$price) {
            return 0;
        }

        $length = strlen($discount);
        $base = '1';

        for ($i = 0; $i < $length; $i++) {
            $base .= '0';
        }

        return $price*$discount/$base;
    }

    /**
     * 判断当前是否在购物车中
     * @param  int
     * @param  int|integer
     * @return [type]
     */
    public static function in_cart($sku_id, $is_promotion = 0)
    {
        if (!$sku_id) {
            return false;
        }

        $cart_list = self::get_list();
        if (!$cart_list || empty($cart_list)) {
            return false;
        }

        foreach ($cart_list as $k=>$v) {
            if ($v['sku_id'] == $sku_id && $is_promotion == $v['is_promotion']) {
                return true;
            }
        }

        return false;
    }

    /**
     * 获取购物车内某个sku的数量
     * @param  int
     * @param  int|integer
     * @return [type]
     */
    public static function get_sku_num($sku_id)
    {
        if (!$sku_id) {
            return 0;
        }

        $cart_list = self::get_list();
        if (!$cart_list || empty($cart_list)) {
            return 0;
        }

        foreach ($cart_list as $k=>$v) {
            if ($v['sku_id'] == $sku_id && $v['is_promotion'] == 0 && $v['is_gift'] == 0) {
                return $v['goods_num'];
            }
        }

        return 0;
    }

    /**
     * 判断当前商品是否在购物车中
     * @param  int
     * @param  int|integer
     * @return [type]
     */
    public static function goods_in_cart($goods_id, $is_promotion = 1, $sku_id = 0)
    {
        if (!$goods_id) {
            return false;
        }

        $cart_list = self::get_list();
        if (!$cart_list || empty($cart_list)) {
            return false;
        }

        foreach($cart_list as $k=>$v) {
            if ($v['is_promotion'] == $is_promotion && $v['goods_id'] == $goods_id && $v['is_gift'] == 0) {
                return $v['sku_id'];
            }
        }

        return false;
    }

    /**
     * 获取单条购物车内商品信息
     * @param  int
     * @param  int
     * @param  int
     * @return [type]
     */
    public static function get_cart_info($sku_id, $goods_num, $is_promotion, $is_gift = 0, $is_all = 0)
    {
        $info = array();
        $sku_info   = _uri('sku', $sku_id);
        if (!$sku_info) {
            return array();
        }
        $goods_id   = $sku_info['goods_id'];
        $goods_info = _uri('goods', $goods_id);
        if (!$goods_info) {
            return array();
        }

        $info['goods_id']    = $goods_info['id'];
        $info['goods_title'] = $goods_info['title'];
        $info['goods_cover'] = goods_helper::sku_cover($sku_id);
        $info['sku_id']      = $sku_id;
        $info['goods_price'] = $sku_info['price'];
        $info['stock']       = $sku_info['stock'];
        $info['goods_num']   = $goods_num;
        $info['is_promotion']= $is_promotion;
        $info['is_gift']     = $is_gift;
        $info['goods_notice'] = $goods_info['goods_notice'];
        if ($sku_info['stock'] < $goods_num) {
            if ($sku_info['stock'] < 1) {
                $sku_info['stock'] = 1;
            }
            $info['goods_num'] = $sku_info['stock'];
        }
        if ($is_promotion > 0) {
            $info['goods_num']   = 1; // 加价购商品只能有1件
            $info['goods_price'] = _uri('promotion_add', array('goods_id'=>$goods_id), 'sale_price');
        }
        if ($is_gift == 0 && $is_promotion == 0 && $is_all == 0) {
            $gift_list = array();
            $cart_list = self::get_list();
            foreach ($cart_list as $k=>$v) {
                if ($v['parent_sku_id'] == $sku_id) {
                    $goods_info = _uri('goods', $v['goods_id']);
                    $gift_list[] = array(
                            'goods_id'  => $v['goods_id'],
                            'goods_num' => $v['goods_num'],
                            'sku_id'    => $v['sku_id'],
                            'gift_num'  => _uri('goods_gift_relation', array('goods_id'=>$v['parent_id'], 'gift_sku_id'=>$v['sku_id']), 'gift_num'),
                            'goods_title' => $goods_info['title']
                        );
                }
            }
            $info['gift_detail'] = $gift_list;
        }
        if ($is_gift == 1) {
            $info['goods_price'] = 0;
        }

        return $info;
    }

    /**
     * 显示满减信息com
     * @return string
     */
    public static function view_promotion_sub()
    {
        $price = self::get_cart_price_total(false);

        $promotion_info = promotion_helper::get_promotion_info($price);
        if ($promotion_info) {
            return '<p class="prompt"><i class="ico">满减</i>活动商品已购满'.number_format($promotion_info['limit_price'], 2).'元，已减'.number_format($promotion_info['offer_price'], 2).'元</p>';
        }

        return '';
    }

    /**
     * 按支付宝的来分类购物车内容
     */
    public static function category_cart_by_alipay_account($cart_list = NULL)
    {
        if(NULL === $cart_list) {
            $cart_list = _widget('cart')->get_list(array('is_all'=>1));
        }
        if(!$cart_list) {
            return array();
        }
        $category_cart_list  = array();

        foreach ($cart_list as $k=>$v) {
            if(empty($v['goods_id'])) {
                continue;
            }
            $goods_info = _uri('goods', $v['goods_id']);
            if(!isset($category_cart_list[$goods_info['alipay_account']])) {
                $category_cart_list[$goods_info['alipay_account']] = array();
            }
            $category_cart_list[$goods_info['alipay_account']][] = $v;
        }
        return $category_cart_list;
    }
}
?>